<template>
  <VDFullScreen>
    <v-card :style="appStyle">
      <v-row style="padding:0">
        <v-col style="padding:0" cols="4">
          <v-row style="padding:0">
            <v-col style="padding:0" cols="2">

            </v-col>
            <v-col style="padding:15px 0 0 0;margin-bottom:-15px" cols="9">
              <v-select dark dense v-model="plantCode"   solo solo-inverted item-text="text" item-value="value" :items="plantItems"  ></v-select>
            </v-col>
            <v-col style="padding:0" cols="1"></v-col>
          </v-row>
          <v-row style="padding:0">
            <v-col style="padding:0" cols="2"></v-col>
            <v-col style="padding:0"  cols="3">
              <v-switch dark
                        v-model="auto"
                        inset
                        :label="`${autoName}`"
                        color="success"
                        class="mt-1"
              ></v-switch>
            </v-col>
            <v-col style="padding:0 3px 0 0" cols="3">
              <v-select v-show="auto" style="font-size:13px" solo solo-inverted  dense item-text="text" item-value="value" :items="refreshDataTimeItems"  v-model="refreshDataTime" dark></v-select>
            </v-col>
            <v-col style="padding:0 0 0 2px" cols="3">
              <v-select  style="font-size:13px" solo solo-inverted  dense item-text="text" item-value="value" :items="pageSizeItems"  v-model="pageSize" dark></v-select>
            </v-col>
            <v-col style="padding:0;" cols="1">
            </v-col>
          </v-row>
        </v-col>


        <v-col cols="4" style="display:flex;justify-content:center">
          <div :style="topImage"></div>
        </v-col>
        <v-col style="padding:15px 0 0 0;" cols="1">
          <v-tooltip bottom>
            <template v-slot:activator="{ on, attrs }">
              <v-btn icon color="success" @click="exportToExcel" class="ma-1" v-bind="attrs" v-on="on">
                <v-icon>mdi-file-excel</v-icon>
              </v-btn>
            </template>
            <span>导出Excel</span>
          </v-tooltip>
          <v-btn class="ma-1" text color="#8D9957" @click="toConf">
            <v-icon>mdi-cog</v-icon>
          </v-btn>
        </v-col>
        <v-col style="padding:0;" cols="2">
          <div :style="tipsbg">
            <v-row style="padding-top:13px">
              <h3 style="color:#18FFFF;font-weight:bold;padding:0 0 0 60px">退出标准-状态说明</h3>
            </v-row>
            <v-row style="padding:3px 0px 0px 22px;width:250px">
              <v-col style="padding:0px 1px 0px 0px" cols="6"><h4 style="background-color:red;font-weight:bold;line-height:28px;width:115px;text-align:center;border-radius:5px;color:#FFFFFF">R:逾期未完成</h4></v-col>
              <v-col style="padding:0px 1px 0px 0px" cols="6"><h4 style="background-color:#37474F;font-weight:bold;line-height:28px;width:115px;text-align:center;border-radius:5px;color:#FFFFFF">N/A:不适用</h4></v-col>
            </v-row>
            <v-row style="padding:5px 0 0 22px;width:250px">
              <v-col style="padding:0px 1px 2px 0px" cols="6"><h4 style="background-color:#F9A825;font-weight:bold;line-height:28px;width:115px;text-align:center;border-radius:5px;color:#FFFFFF">Y:需要但未完成</h4></v-col>
              <v-col style="padding:0px 1px 2px 0px" cols="6"><h4 style="background-color:#2E7D32;font-weight:bold;line-height:28px;width:115px;text-align:center;border-radius:5px;color:#FFFFFF">G:完成</h4></v-col>
            </v-row>
          </div>
        </v-col>
        <v-col cols="1" style="padding:0;display:flex;justify-content:end">
          <v-btn v-show="!is_fullscreen" class="ma-1" text color="#8D9957" @click="fullscreen">
            <v-icon >mdi-fullscreen</v-icon>
          </v-btn>
          <v-btn v-show="is_fullscreen" class="ma-1" text color="#8D9957" @click="fullscreenExit">
            <v-icon >mdi-fullscreen-exit</v-icon>
          </v-btn>
        </v-col>
      </v-row>
      <v-row  >
        <v-col style="padding:0 0 0 40px" cols="10">
          <v-row >
            <v-col style="padding: 12px 3px 18px 0px" cols="2">
              <VZDatePicker class="ma-1" v-model="dates" label="时间范围" type="daterange" dark></VZDatePicker>
            </v-col>
            <v-col  style="padding:12px 3px 0 3px" cols="1">
              <v-select class="ma-1" dense :items="eventTypeItems" label="事件类型" item-text="name" item-value="code" v-model="eventType" dark></v-select>
            </v-col>
            <v-col  style="padding:12px 0 0 3px" cols="1">
              <v-select class="ma-1" dense :items="problemTypeItems" label="问题类型" item-text="name" item-value="code" v-model="problemType" dark></v-select>
            </v-col>


            <v-col style="padding:12px 0 0 3px" cols="2">
              <v-combobox dense class="ma-1" style="padding:0" v-model="workshop" :items="workshopItems" label="车间"  dark></v-combobox>
            </v-col>

            <v-col style="padding:12px 0 0 3px" cols="2">
              <v-combobox dense class="ma-1" style="padding:0" v-model="department" :items="departmentItems" label="责任部门"  dark></v-combobox>
            </v-col>

            <v-col style="padding:12px 0 0 3px" cols="2">
              <v-combobox dense class="ma-1" style="padding:0" v-model="launchPerson" :items="launchPersonItems" label="问题发起人"  dark></v-combobox>
            </v-col>

            <v-col style="padding:12px 0 0 3px" cols="2">
              <v-combobox dense class="ma-1" style="padding:0" v-model="launchPersonBase" :items="launchPersonBaseItems" label="问题提出公司"  dark></v-combobox>
            </v-col>

          </v-row>
        </v-col>
        <v-col style="padding:0 0 0 15px" cols="2">
          <v-btn class="ma-1" outlined color="info" dark @click="search">查询</v-btn>
          <v-btn class="ma-1" outlined color="#8D9957" dark @click="reset">重置</v-btn>
        </v-col>
      </v-row>
      <v-row align="center">
        <v-col style="padding-top:0px;" cols="12">
          <v-data-table
                  :headers="dessertHeaders"
                  :items="desserts"
                  no-data="没有数据"
                  calculate-widths=true
                  height=65vh
                  class="elevation-1"
                  hide-default-footer="true"
                  :options.sync="options"
                  dense
                  fixed-header = "true"
                  style="cursor:pointer;margin-left:20px;margin-right:20px"
          >
            <template
                    v-slot:header="{ props: { headers } }">
              <thead  >
              <tr style="text-align:center;">
                <th :colspan="14">
                </th>
                <th :colspan="1" style="text-align:center;border-left:1px solid #aaa;border-right:1px solid #aaa">
                  24H
                </th>
                <th :colspan="1" style="text-align:center;">
                  7D
                </th>
                <th :colspan="3" style="text-align:center;border-left:1px solid #aaa;border-right:1px solid #aaa">
                  14D
                </th>
                <th :colspan="1" style="text-align:center;">
                  28D
                </th>
                <th :colspan="1" style="text-align:center;border-left:1px solid #aaa;border-right:1px solid #aaa">
                  29D
                </th>
                <th :colspan="1" style="text-align:center;border-right:1px solid #aaa">
                  31D
                </th>
                <th :colspan="1">
                </th>
              </tr>
              </thead>
            </template>
            <template v-slot:header.problemCode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.problemTitle="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.eventType="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.qualityProblemType="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.problemDesc="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.qualityProblemSeverity="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.measureInterim="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.planDateInterim="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.actualDateInterim="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.rootCause="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.measureLongTerm="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.planDateLongTerm="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.actualDateLongTerm="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.chargePersonNameDept="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.nextReportTime="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.emergencyMeasureNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.rootCauseNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.longTermMeasureNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.errorProofNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.hierarchicalAuditNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.longTermMeasureVerifyNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.pfmeaNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <!--<template v-slot:header.operationInstructionNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>-->
            <template v-slot:header.lessonsLearnNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>
            <template v-slot:header.currentStatusNode="{ header }">
              <span :style="headerStyle">{{ header.text }}</span>
            </template>

            <template
                    v-slot:body="{ items }"
            >

              <tbody>
              <tr
                      v-for="item in items"
                      :key="item.problemId"
              >
                <td align=center style="padding:3px;">

                  <v-tooltip top>
                    <template v-slot:activator="{ on, attrs }">
                      <v-btn style="padding:0" v-on="on" text color="warning" v-bind="attrs"  @click="updateProblem(item.problemId,item.problemProcessId,item.processInstanceId)">{{ item.problemCode }}</v-btn>

                    </template>
                    <span>编辑</span>
                  </v-tooltip>
                </td>
                <td align=center style="padding:3px;">{{ item.createTime }}</td>
                <td align=center style="padding:3px;">{{ item.problemClass }}</td>
                <td align=center style="padding:3px;">问题现象:{{ item.phenomenon }}
                  What:{{ item.what }}
                  Why:{{ item.forWhatReason }}
                  Who:{{ item.who }}
                  When:{{ item.whenTime }}
                  Where:{{ item.wherePlace }}
                  How:{{ item.how }}
                  How much:{{ item.amount }}
                </td>
                <!--                 private String who;
                    private String what;
                    private String wherePlace;
                    private String whenTime;
                    private String forWhatReason;
                    private String how;
                    private String amount;
                -->
                <td align=center style="padding:3px;">{{ item.qualityProblemSeverity }}</td>
                <td align=center style="padding:3px;">遏制措施:{{ item.stressActivities }}  短期措施:{{ item.measureInterim }}  断点时间:{{ item.implementedDate }}</td>
                <td align=center style="padding:3px;">{{ item.planDateInterim }}</td>
                <td align=center style="padding:3px;">{{ item.actualDateInterim }}</td>
                <td align=center style="padding:3px;">{{ item.rootCause }}</td>
                <td align=center style="padding:3px;">{{ item.measureLongTerm }}</td>
                <td align=center style="padding:3px;">{{ item.planDateLongTerm }}</td>
                <td align=center style="padding:3px;">{{ item.actualDateLongTerm }}</td>
                <td align=center style="padding:3px;">{{ item.chargePersonNameDept }}</td>
                <td align=center style="padding:3px;">{{ item.nextReportTime }}</td>
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.emergencyMeasureNode)" dark>{{ item.emergencyMeasureNode }}</v-chip></td>
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.rootCauseNode)" dark>{{ item.rootCauseNode }}</v-chip></td>
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.longTermMeasureNode)" dark>{{ item.longTermMeasureNode }}</v-chip></td>
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.errorProofNode)" dark>{{ item.errorProofNode }}</v-chip></td>
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.hierarchicalAuditNode)" dark>{{ item.hierarchicalAuditNode }}</v-chip></td>
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.longTermMeasureVerifyNode)" dark>{{ item.longTermMeasureVerifyNode }}</v-chip></td>
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.pfmeaNode)" dark>{{ item.pfmeaNode }}</v-chip></td>
                <!--<td align=center style="padding:3px;"><v-chip :color="getColor(item.operationInstructionNode)" dark>{{ item.operationInstructionNode }}</v-chip></td>-->
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.lessonsLearnNode)" dark>{{ item.lessonsLearnNode }}</v-chip></td>
                <td align=center style="padding:3px;"><v-chip :color="getColor(item.currentStatusNode)" dark>{{ item.currentStatusNode }}</v-chip></td>
              </tr>
              </tbody>
            </template>


            <!-- <template v-slot:item.problemCode="{ item }">
               <v-tooltip top>
                 <template v-slot:activator="{ on, attrs }">
                   <v-btn style="padding:0" v-on="on" text color="warning" v-bind="attrs"  @click="updateProblem(item.problemId,item.problemProcessId,item.processInstanceId)">{{ item.problemCode }}</v-btn>
                 </template>
                 <span>编辑</span>
               </v-tooltip>
             </template>

             <template v-slot:item.rootCause="{ item }"><span style="padding:2px 0 2px 0" :color="getColor(item.rootCause)" dark>{{ item.rootCause }}</span></template>

             <template v-slot:item.emergencyMeasureNode="{ item }"><v-chip :color="getColor(item.emergencyMeasureNode)" dark>{{ item.emergencyMeasureNode }}</v-chip></template>
             <template v-slot:item.rootCauseNode="{ item }"><v-chip :color="getColor(item.rootCauseNode)" dark>{{ item.rootCauseNode }}</v-chip></template>
             <template v-slot:item.longTermMeasureNode="{ item }"><v-chip :color="getColor(item.longTermMeasureNode)" dark>{{ item.longTermMeasureNode }}</v-chip></template>
             <template v-slot:item.errorProofNode="{ item }"><v-chip :color="getColor(item.errorProofNode)" dark>{{ item.errorProofNode }}</v-chip></template>
             <template v-slot:item.hierarchicalAuditNode="{ item }"><v-chip :color="getColor(item.hierarchicalAuditNode)" dark>{{ item.hierarchicalAuditNode }}</v-chip></template>
             <template v-slot:item.longTermMeasureVerifyNode="{ item }"><v-chip :color="getColor(item.longTermMeasureVerifyNode)" dark>{{ item.longTermMeasureVerifyNode }}</v-chip></template>
             <template v-slot:item.pfmeaNode="{ item }"><v-chip :color="getColor(item.pfmeaNode)" dark>{{ item.pfmeaNode }}</v-chip></template>
             <template v-slot:item.operationInstructionNode="{ item }"><v-chip :color="getColor(item.operationInstructionNode)" dark>{{ item.operationInstructionNode }}</v-chip></template>
             <template v-slot:item.lessonsLearnNode="{ item }"><v-chip :color="getColor(item.lessonsLearnNode)" dark>{{ item.lessonsLearnNode }}</v-chip></template>
             <template v-slot:item.currentStatusNode="{ item }"><v-chip :color="getColor(item.currentStatusNode)" dark>{{ item.currentStatusNode }}</v-chip></template>-->
          </v-data-table>
        </v-col>
      </v-row>
      <div class="text-center">
        <v-pagination
                v-model="page"
                :length="totalPage"
                :total-visible="10"

                circle
                @input="clickInput"
        ></v-pagination>
      </div>
    </v-card>
  </VDFullScreen>
</template>
<script>
  export default {
    data () {
      return {
        is_fullscreen:false,
        dates:[],
        intervalId: null,
        sourceItems:[
          {
            text:'HV内部',
            value:'INTERNAL',
          },
          {
            text:'HV外部',
            value:'EXTERNAL',
          },
        ],
        problemTypeItems:app.utils.getEntrys("QUALITY_PROBLEM_TYPE"),
        eventTypeItems:app.utils.getEntrys("QUALITY_EVENT_TYPE"),
        problemType:'FAST_REVERSAL_PROBLEM',
        eventType:'OPERATE',
        pageSizeItems:[
          {text:'1条/页',value:1},
          {text:'5条/页',value:5},
          {text:'10条/页',value:10},
          {text:'20条/页',value:20},
        ],
        refreshDataTimeItems:[
          {text:'15秒翻页',value:15},
          {text:'30秒翻页',value:30},
          {text:'60秒翻页',value:60},
          {text:'120秒翻页',value:120},
        ],
        refreshDataTime:60,
        departmentItems:[],
        department:'',
        problemSource:'',
        auto:false,
        workshopItems:[],
        workshop:'',
        page:1,
        totalCount:0,
        totalPage:0,
        pageSize:5,
        dessertHeaders: [
          {
            text: '问题编号',
            align: 'center',
            value: 'problemCode',
            sortable: false,
            width:60
          },
          { text: '创建时间', value: 'createTime',sortable: false,align: 'center',width:85},
          { text: '问题大类', value: 'problemClass',sortable: false,align: 'center',width:60},
          { text: '问题描述', value: 'problemDesc',sortable: false,align: 'center',width:200},
          { text: '严重度', value: 'qualityProblemSeverity',sortable: false ,align: 'center',width:30 },
          { text: '遏制措施/临时措施', value: 'measureInterim' ,sortable: false,align: 'center',width:200 },
          // { text: '遏制措施', value: 'stressActivities' ,sortable: false,align: 'center',width:80 },

          // { text: '问题名称', value: 'problemTitle',sortable: false,align: 'center',width:60},
          // { text: '事件类型', value: 'eventType',sortable: false ,align: 'center',width:60 },
          // { text: '问题类型', value: 'qualityProblemType',sortable: false ,align: 'center',width:60 },
          // { text: '问题描述', value: 'problemDesc',sortable: false ,align: 'center',width:60 },



          { text: '计划时间', value: 'planDateInterim',sortable: false ,align: 'center',width:90 },
          { text: '实际时间', value: 'actualDateInterim',sortable: false ,align: 'center',width:90 },
          { text: '根本原因', value: 'rootCause',sortable: false ,align: 'center',width:110 },
          { text: '长期措施', value: 'measureLongTerm',sortable: false ,align: 'center',width:200 },
          { text: '计划时间', value: 'planDateLongTerm' ,sortable: false,align: 'center' ,width:50},
          { text: '实际时间', value: 'actualDateLongTerm' ,sortable: false ,align: 'center',width:50},
          { text: '问题责任人', value: 'chargePersonNameDept',sortable: false ,align: 'center',width:60 },
          { text: '下次汇报时间', value: 'nextReportTime' ,sortable: false,align: 'center',width:60 },
          { text: '遏制', value: 'emergencyMeasureNode' ,sortable: false,align: 'center',width:30 },
          { text: '根本原因分析', value: 'rootCauseNode' ,sortable: false,align: 'center',width:50 },
          { text: '纠正措施', value: 'longTermMeasureNode',sortable: false ,align: 'center',width:30 },
          { text: '防错检验', value: 'errorProofNode' ,sortable: false,align: 'center' ,width:30},
          { text: '分层审核', value: 'hierarchicalAuditNode',sortable: false,align: 'center',width:30  },
          { text: '纠正措施验证', value: 'longTermMeasureVerifyNode' ,sortable: false ,align: 'center',width:30},
          { text: '文件更新', value: 'pfmeaNode',sortable: false,align: 'center',width:30 ,},
          /*{ text: '作业指导书更新', value: 'operationInstructionNode',sortable: false  ,width:65},*/
          { text: '经验教训', value: 'lessonsLearnNode',sortable: false ,align: 'center',width:30 },
          { text: '当前状态', value: 'currentStatusNode' ,sortable: false ,align: 'center',width:30},
        ],
        desserts: [],
        plantItems:[],
        plantCode:'',
        departmentConf:'-1',
        launchPersonDeptSql:"SELECT LAUNCH_PERSON_ID id, LAUNCH_PERSON_NAME NAME  FROM tb_quality_problem  WHERE LAUNCH_PERSON_ID IS NOT NULL  AND MARK_FOR_DELETE = 0 GROUP BY LAUNCH_PERSON_ID",
        launchPersonItems:[],
        launchPerson :'',
        launchPersonBaseItems:[],
        launchPersonBase:'',
        options: {
          itemsPerPage: 5, // 这里设置每页显示 5 条数据
        },
      }
    },
    methods: {
      toConf(){
        this.$emit('toPage', 'va04be128ac4fab9aec7cf15bf0', {});
      },
      vRefresh(){
        this.loadDepartmentData();
        this.search();
      },
      updateProblem(problemId,problemProcessId,processInstanceId){
        if(this.auto){
          app.utils.showMessage("请切换至手动模式再查看详情！","warning");
          return;
        }
        this.$emit('toPage', 've97a65cfd44505b51d598f0231', {"problem_id":problemId,"problem_process_id":problemProcessId,"process_instance_id":processInstanceId});
      },
      clickInput(){
        this.search();
      },
      getColor(data){
        if(data == "G"){
          return '#2E7D32';
        }else if(data == "Y"){
          return '#F9A825';
        }else if(data == "R"){
          return 'red';
        }else {
          return '#37474F';
        }
      },
      show(){
        app.utils.showMessage(this.prop);
      },
      reset(){
        this.dates=[];
        this.problemSource = '',
                this.workshop='';
        this.department='';
        this.launchPerson='';
        this.launchPersonBase='';
        this.problemType='';
        this.eventType='';
        this.search();
      },
      search(){
        let startDate = '';
        let endDate = '';
        let _this = this;
        if(this.dates.length > 0){
          startDate = this.dates[0];
          if(this.dates.length > 1){
            endDate = this.dates[1];
          }
        }
        let departmentConf = '';
        if(this.problemType && this.problemType == 'FAST_REVERSAL_PROBLEM'){
          departmentConf = '';
        }else{
          departmentConf = this.departmentConf;
        }
        
        // 构建查询参数
        let params = {
          "rows":this.pageSize,
          "limit":this.pageSize,
          "offset":(this.page-1)*this.pageSize,
          "page":this.page,
          "queryCondition[plantCode]":_this.plantCode,
          "queryCondition[problemStatusIN]":'CLOSED,RELEASE',
          "queryCondition[ifHidden]": 'N',
        };
        
        // 添加可选参数，只有当有值时才添加到查询条件中
        if(_this.problemType) {
          params["queryCondition[qualityProblemType]"] = _this.problemType;
        }
        
        if(_this.eventType) {
          params["queryCondition[eventType]"] = _this.eventType;
        }
        
        // 处理车间参数
        if(_this.workshop && _this.workshop.value) {
          params["queryCondition[workshopCode]"] = _this.workshop.value;
        }
        
        // 处理责任部门参数
        if(_this.department && _this.department.value) {
          params["queryCondition[chargePersonDeptId]"] = _this.department.value;
        }
        
        // 处理问题发起人参数
        if(_this.launchPerson && _this.launchPerson.id) {
          params["queryCondition[launchPersonId]"] = _this.launchPerson.id;
        }
        
        // 处理问题提出公司参数
        if(_this.launchPersonBase && _this.launchPersonBase.value) {
          params["queryCondition[launch_person_base]"] = _this.launchPersonBase.value;
        }
        
        // 添加时间范围参数
        if(startDate) {
          params["queryCondition[problemHappenDateStart]"] = startDate;
        }
        
        if(endDate) {
          params["queryCondition[problemHappenDateEnd]"] = endDate;
        }
        
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_FAST_RESPONSE_PROBLEM_LIST",
          params: params,
          callBack(res) {
            _this.desserts = [];
            if(res.success){
              _this.totalPage = res.totalPage;
              res.rows.forEach((item) => {
                item.problemSource = app.utils.getEntryValue("QUALITY_PROBLEM_SOURCE", item.problemSource);
                item.qualityProblemType = app.utils.getEntryValue("QUALITY_PROBLEM_TYPE", item.qualityProblemType);
                item.eventType = app.utils.getEntryValue("QUALITY_EVENT_TYPE", item.eventType);
              })
              _this.desserts = res.rows;
            }
          },
        })
      },
      loadPlantData() {
        let _this = this;
        _this.plantItems = [];
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_PLANT_SELECT",
          params: {is_queryPage:false,"rows":100,"limit":100,"offset":0,"page":1,sort:'plant_code',order:'asc',"queryCondition[if_show]":"Y"},
          callBack(res) {
            if(res.success && res.rows.length > 0){
              let dataList = res.rows;
              let plantList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.plant_name;
                map.value = item.plant_code;
                map.id = item.id;
                plantList.push(map);
              })
              _this.plantItems = plantList;
            }
          },
        })
      },
      loadWorkshopData() {
        let _this = this;
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_WORKSHOP_SELECT",
          params: {is_queryPage:false,"queryCondition[plant_id.plant_code]":_this.plantCode},
          callBack(res) {
            if(res.success && res.rows.length > 0){
              let dataList = res.rows;
              let workshopList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.workshop_name;
                map.value = item.workshop_code;
                map.id = item.id;
                workshopList.push(map);
              })
              _this.workshopItems = workshopList;
            }else{
              _this.workshopItems = [];
            }
          },
        })
      },
      // 获取问题发起人
      loadLaunchPersonData() {
        let _this = this;
        _this.launchPersonItems = [];
        let params = {"SQL": this.launchPersonDeptSql};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let launchPersonList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                launchPersonList.push(map);
              })
              _this.launchPersonItems = launchPersonList;
            }
          },
        })
      },
      loadLaunchPersonBaseData() {
        let _this = this;
        _this.launchPersonBaseItems = [];
        let params = {"SQL": "SELECT DISTINCT LAUNCH_PERSON_BASE FROM tb_quality_problem WHERE LAUNCH_PERSON_BASE IS NOT NULL AND MARK_FOR_DELETE = 0"};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let launchPersonBaseList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.launch_person_base;
                map.value = item.launch_person_base;
                launchPersonBaseList.push(map);
              })
              _this.launchPersonBaseItems = launchPersonBaseList;
            }
          },
        })
      },
      loadDepartmentData() {
        let _this = this;

        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_FAST_RESPONSE_DEPARTMENT_SELECT",
          params: {"rows":1000,"limit":1000,"offset":0,"page":1},
          callBack(res) {
            if(res.success && res.rows.length > 0){
              let dataList = res.rows;
              let departmentList = [];
              let department_conf = '';
              dataList.forEach((item) => {
                let map = {};
                map.text = item.organization_name;
                map.value = item.organization_id;
                departmentList.push(map);
                department_conf += (item.organization_id + ",");
              })
              _this.departmentItems = departmentList;
              _this.departmentConf = department_conf;
            }else{
              _this.departmentItems = [];
              _this.departmentConf = '-1';
            }
          },
        })
      },
      autoPage(){
        if(this.totalPage > this.page){
          this.page ++;
          this.search();
        }else if(this.totalPage == this.page && this.totalPage != 1 && this.totalPage != 0){
          this.page = 1;
          this.search();
        }
      },
      fullscreen(){
        this.launchFullscreen(document.documentElement);
        this.is_fullscreen = true;
      },
      launchFullscreen(element) {
        if (element.requestFullscreencreen) {
          element.requestFullScreen();
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen();
        } else if (element.webkitRequestFullScreen) {
          element.webkitRequestFullScreen();
        } else if (element.msRequestFullScreen) {
          element.msRequestFullScreen();
        }
      },
      fullscreenExit(){
        document.exitFullscreen();
        this.is_fullscreen = false;
      },
      exportToExcel() {
        if (this.desserts.length === 0) {
          app.utils.showMessage("暂无数据可导出", "warning");
          return;
        }

        try {
          // 构建查询参数，获取所有数据
          let _this = this;
          let params = {
            "rows": 10000, // 设置一个足够大的数字来获取所有数据
            "limit": 10000,
            "offset": 0,
            "page": 1,
            "queryCondition[plantCode]": _this.plantCode,
            "queryCondition[problemStatusIN]": 'CLOSED,RELEASE',
            "queryCondition[ifHidden]": 'N',
          };
          
          // 添加可选参数，只有当有值时才添加到查询条件中
          if(_this.problemType) {
            params["queryCondition[qualityProblemType]"] = _this.problemType;
          }
          
          if(_this.eventType) {
            params["queryCondition[eventType]"] = _this.eventType;
          }
          
          // 处理车间参数
          if(_this.workshop && _this.workshop.value) {
            params["queryCondition[workshopCode]"] = _this.workshop.value;
          }
          
          // 处理责任部门参数
          if(_this.department && _this.department.value) {
            params["queryCondition[chargePersonDeptId]"] = _this.department.value;
          }
          
          // 处理问题发起人参数
          if(_this.launchPerson && _this.launchPerson.id) {
            params["queryCondition[launchPersonId]"] = _this.launchPerson.id;
          }

          // 处理问题提出公司参数
          if(_this.launchPersonBase && _this.launchPersonBase.value) {
            params["queryCondition[launch_person_base]"] = _this.launchPersonBase.value;
          }
          
          // 添加时间范围参数
          if(this.dates.length > 0){
            params["queryCondition[problemHappenDateStart]"] = this.dates[0];
            if(this.dates.length > 1){
              params["queryCondition[problemHappenDateEnd]"] = this.dates[1];
            }
          }

          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_FAST_RESPONSE_PROBLEM_LIST",
            params: params,
            callBack(res) {
              if(res.success && res.rows.length > 0){
                // 创建CSV内容
                let csvContent = '\uFEFF'; // 添加BOM以支持中文
                
                // 添加表头
                const headers = [
                  '问题编号',
                  '创建时间',
                  '问题大类',
                  '问题描述',
                  '严重度',
                  '遏制措施/临时措施',
                  '计划时间',
                  '实际时间',
                  '根本原因',
                  '长期措施',
                  '计划时间',
                  '实际时间',
                  '问题责任人',
                  '下次汇报时间',
                  '遏制',
                  '根本原因分析',
                  '纠正措施',
                  '防错检验',
                  '分层审核',
                  '纠正措施验证',
                  '文件更新',
                  '经验教训',
                  '当前状态',
                  '问题发起人',
                  '问题来源'
                ];
                csvContent += headers.join(',') + '\n';
                
                // 添加数据行
                res.rows.forEach(item => {
                  const row = [
                    item.problemCode,
                    item.createTime,
                    item.problemClass,
                    `"${item.phenomenon || ''} What:${item.what || ''} Why:${item.forWhatReason || ''} Who:${item.who || ''} When:${item.whenTime || ''} Where:${item.wherePlace || ''} How:${item.how || ''} How much:${item.amount || ''}"`,
                    item.qualityProblemSeverity,
                    `"遏制措施:${item.stressActivities || ''} 短期措施:${item.measureInterim || ''} 断点时间:${item.implementedDate || ''}"`,
                    item.planDateInterim,
                    item.actualDateInterim,
                    `"${item.rootCause || ''}"`,
                    `"${item.measureLongTerm || ''}"`,
                    item.planDateLongTerm,
                    item.actualDateLongTerm,
                    item.chargePersonNameDept,
                    item.nextReportTime,
                    item.emergencyMeasureNode,
                    item.rootCauseNode,
                    item.longTermMeasureNode,
                    item.errorProofNode,
                    item.hierarchicalAuditNode,
                    item.longTermMeasureVerifyNode,
                    item.pfmeaNode,
                    item.lessonsLearnNode,
                    item.currentStatusNode,
                    item.launchPersonName,
                    app.utils.getEntryValue("QUALITY_PROBLEM_SOURCE", item.problemSource)
                  ];
                  csvContent += row.join(',') + '\n';
                });

                // 创建Blob对象
                const BOM = '\uFEFF';
                const csvData = BOM + csvContent;
                const blob = new Blob([csvData], { type: 'application/vnd.ms-excel;charset=utf-8' });
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                const now = new Date();
                const timestamp = now.getFullYear() + 
                                String(now.getMonth() + 1).padStart(2, '0') + 
                                String(now.getDate()).padStart(2, '0') + 
                                String(now.getHours()).padStart(2, '0') + 
                                String(now.getMinutes()).padStart(2, '0') + 
                                String(now.getSeconds()).padStart(2, '0');
                link.download = `问题列表_${timestamp}.csv`;
                
                // 触发下载
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(link.href);
                
                app.utils.showMessage("导出成功", "success");
              } else {
                app.utils.showMessage("暂无数据可导出", "warning");
              }
            },
          });
        } catch (error) {
          console.error('导出失败:', error);
          app.utils.showMessage("导出失败，请稍后重试", "error");
        }
      },
    },
    computed: {
      autoName: function () {
        return this.auto ? '自动':'手动';
      },
      appStyle:function () {
        let bgImage = app.path().res + "images/mda/factoryallBg.png";
        //let bgImage = app.path().res + "images/main/auth/login.jpg";
        return {
          backgroundImage: `url(${bgImage})`,
          backgroundPosition: " center center",
          backgroundSize: "cover",
          height:'93vh',
          width:'100vw'
        }
      },
      topImage:function () {
        let bgImage = app.path().res + "images/mda/T2.png"
        return {
          backgroundImage: `url(${bgImage})`,
          backgroundPosition: " center center",
          backgroundSize: "cover",
          height:'60px',
          width:'30vw',
          padding:0
        }
      },
      tipsbg:function () {
        let bgImage = app.path().res + "images/mda/tipsbg.png"
        return {
          backgroundImage: `url(${bgImage})`,
          backgroundPosition: " center center",
          backgroundSize: "cover",
          height:'125px',
          width:'250px'
        }
      },
      headerStyle:function () {
        return {
          //color: "#18FFFF",
          fontSize: "14px",
          padding:"3px"
        }
      },
    },
    watch:{
      auto(newValue,oldValue){
        clearInterval(this.intervalId);
        this.intervalId = null;
        if(newValue){
          let _this = this;
          let refreshDataTime = this.refreshDataTime * 1000;
          this.intervalId = setInterval(function () {
            _this.autoPage();
          }, refreshDataTime);
        }
      },
      pageSize(newValue){
        this.page = 1 ;
        this.options.itemsPerPage = newValue;
        this.search();
      },
      refreshDataTime(newValue){
        let _this = this;
        clearInterval(this.intervalId);
        this.intervalId = null;
        let refreshDataTime = this.refreshDataTime * 1000;
        this.intervalId = setInterval(function () {
          _this.autoPage();
        }, refreshDataTime);
      },
      plantCode(newValue){
        this.workshop = '';
        this.loadWorkshopData();
        localStorage.setItem("FAST_RESPONSE_PLANT_CODE",newValue);
        this.page = 1 ;
        this.search();
      },
    },
    created(){
      this.loadDepartmentData();
      if(localStorage.getItem("FAST_RESPONSE_PLANT_CODE")){
        this.plantCode = localStorage.getItem("FAST_RESPONSE_PLANT_CODE");
      }else{
        this.plantCode = '1100';
      }
    },
    mounted () {
      this.search();
      this.loadPlantData();
      this.loadWorkshopData();
      this.loadLaunchPersonData();
      this.loadLaunchPersonBaseData();
      /*this.loadDepartmentData();*/

      /*  let _this = this;
    this.intervalId = setInterval(function () {
      _this.autoSearch();
    }, 1000 * 60);*/
    },
    beforeDestroy() {
      clearInterval(this.intervalId);
    },
    /*    props:{
        plant_code:{
          type:String,
          default:'1100'
        }
      }*/
  }
</script>

